/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-10-10 09:30:00
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-10-10 09:30:00
 * @FilePath: \work-tool\my-dev-project\src\views\system\role.tsx
 * @Description: 角色管理页面
 */
import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Tag, Space, Modal, Form, message, Tree } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, UnlockOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Search } = Input;
const { TextArea } = Input;
const { Option } = Select;
const { confirm } = Modal;

// 模拟角色数据
const mockRoles = [
  {
    id: '1',
    name: '超级管理员',
    code: 'super_admin',
    description: '系统最高权限，可访问所有功能',
    status: 'active',
    createTime: '2025-01-10',
    permissions: ['dashboard', 'system', 'system:user', 'system:menu', 'system:role', 'system:department', 'order', 'order:list', 'order:aggregate', 'order:track']
  },
  {
    id: '2',
    name: '系统管理员',
    code: 'system_admin',
    description: '负责系统管理相关功能',
    status: 'active',
    createTime: '2025-01-15',
    permissions: ['dashboard', 'system', 'system:user', 'system:menu', 'system:role', 'system:department']
  },
  {
    id: '3',
    name: '订单管理员',
    code: 'order_admin',
    description: '负责订单管理相关功能',
    status: 'active',
    createTime: '2025-01-20',
    permissions: ['dashboard', 'order', 'order:list', 'order:aggregate', 'order:track']
  },
  {
    id: '4',
    name: '普通用户',
    code: 'normal_user',
    description: '基础功能访问权限',
    status: 'active',
    createTime: '2025-02-01',
    permissions: ['dashboard']
  },
];

// 模拟权限数据（菜单树）
const mockPermissions = [
  {
    key: 'dashboard',
    title: '控制台',
    children: []
  },
  {
    key: 'system',
    title: '系统管理',
    children: [
      { key: 'system:user', title: '用户管理' },
      { key: 'system:menu', title: '菜单管理' },
      { key: 'system:role', title: '角色管理' },
      { key: 'system:department', title: '部门管理' },
    ]
  },
  {
    key: 'order',
    title: '订单管理',
    children: [
      { key: 'order:list', title: '订单列表' },
      { key: 'order:aggregate', title: '订单聚合' },
      { key: 'order:track', title: '订单追踪' },
    ]
  },
];

interface Role {
  id: string;
  name: string;
  code: string;
  description: string;
  status: string;
  createTime: string;
  permissions: string[];
}

const RoleManagement: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>(mockRoles);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState<string>('');
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 打开创建/编辑模态框
  const showModal = (role?: Role) => {
    if (role) {
      setEditingRole(role);
      setSelectedPermissions([...role.permissions]);
      form.setFieldsValue(role);
    } else {
      setEditingRole(null);
      setSelectedPermissions([]);
      form.resetFields();
    }
    setIsModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        const roleData: Role = {
          ...values,
          permissions: selectedPermissions,
        };

        if (editingRole) {
          // 编辑角色
          const updatedRoles = roles.map(r => 
            r.id === editingRole.id ? { ...r, ...roleData } : r
          );
          setRoles(updatedRoles);
          message.success('角色更新成功');
        } else {
          // 创建角色
          const newRole: Role = {
            ...roleData,
            id: `new_${Date.now()}`,
            createTime: new Date().toISOString().split('T')[0],
          };
          setRoles([...roles, newRole]);
          message.success('角色创建成功');
        }
        setIsModalVisible(false);
        form.resetFields();
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  // 删除角色
  const handleDelete = (id: string) => {
    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除该角色吗？删除后可能会影响用户权限',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        setRoles(roles.filter(role => role.id !== id));
        message.success('角色删除成功');
      },
    });
  };

  // 切换角色状态
  const handleToggleStatus = (id: string, currentStatus: string) => {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    const actionText = newStatus === 'active' ? '启用' : '禁用';
    
    confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}该角色吗？${actionText}后角色权限将${newStatus === 'active' ? '生效' : '失效'}`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        setRoles(roles.map(role => 
          role.id === id ? { ...role, status: newStatus } : role
        ));
        message.success(`角色${actionText}成功`);
      },
    });
  };

  // 处理权限选择
  const onCheck = (checkedKeys: React.Key[]) => {
    setSelectedPermissions(checkedKeys.map(key => key.toString()));
  };

  // 表格列配置
  const columns: ColumnsType<Role> = [
    {
      title: '角色ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      key: 'code',
      ellipsis: true,
    },
    {
      title: '角色描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (text: string) => (
        <TextArea rows={1} value={text} readOnly style={{ border: 'none', resize: 'none' }} />
      ),
    },
    {
      title: '权限数量',
      key: 'permissionCount',
      width: 100,
      render: (_, record) => record.permissions.length,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        return <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button size="small" icon={<EditOutlined />} onClick={() => showModal(record)}>
            编辑
          </Button>
          <Button 
            size="small" 
            icon={<UnlockOutlined />} 
            onClick={() => handleToggleStatus(record.id, record.status)}
          >
            {record.status === 'active' ? '禁用' : '启用'}
          </Button>
          <Button 
            size="small" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 过滤后的数据
  const filteredRoles = roles.filter(role => 
    (!searchText || 
     role.name.includes(searchText) || 
     role.code.includes(searchText) || 
     role.description.includes(searchText))
  );

  return (
    <div style={{ padding: 24 }}>
      <Card 
        title="角色管理"
        extra={
          <Space>
            <Search
              placeholder="搜索角色"
              allowClear
              enterButton="搜索"
              size="small"
              onSearch={handleSearch}
            />
            <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
              添加角色
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={filteredRoles}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 创建/编辑角色模态框 */}
      <Modal
        title={editingRole ? "编辑角色" : "创建角色"}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={editingRole || {
            status: 'active',
          }}
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="角色编码"
            rules={[
              { required: true, message: '请输入角色编码' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '角色编码只能包含字母、数字和下划线' },
              { min: 3, message: '角色编码长度不能小于3个字符' }
            ]}
            
          >
            <Input placeholder="请输入角色编码" disabled={!!editingRole} />
          </Form.Item>

          <Form.Item
            name="description"
            label="角色描述"
          >
            <TextArea rows={3} placeholder="请输入角色描述" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="权限配置"
            rules={[{ required: true, message: '请至少选择一项权限' }]}
          >
            <div style={{ border: '1px solid #f0f0f0', borderRadius: '4px', padding: '16px', maxHeight: '400px', overflowY: 'auto' }}>
              <Tree
                checkable
                defaultExpandAll
                checkedKeys={selectedPermissions}
                onCheck={onCheck}
                treeData={mockPermissions}
              />
            </div>
          </Form.Item>

          <Form.Item style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">
                {editingRole ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleManagement;